package ProducerConsumerModel;

public class Desk {
    private final String[] arr;
    private int size = 0;
    private int head = 0;
    private int tail = 0;

    //有参构造器
    public Desk(int size) {
        this.arr = new String[size];
    }

    //无参构造器,默认大小为10
    public Desk(){
        this.arr = new String[10];
    }

    //放入数据
    public synchronized void put(String data) throws InterruptedException {
        String name = Thread.currentThread().getName();
        String putData = name + ",放入一个数据:" + data;
        if ( ! (size >= arr.length) ){
            arr[tail] = putData;
            tail++;
            if (tail >= arr.length){
                tail = 0;
            }
            size++;
            System.out.println(name + "成功放入数据:" + data + ",当前数据个数为:" + size + "个");
            Thread.sleep(1000);
            this.notifyAll();
            this.wait();
        }else {
            this.notifyAll();
            this.wait();
        }
    }
    //取出数据
    public synchronized void take() throws InterruptedException {
        String name = Thread.currentThread().getName();
        if ( !(size == 0)){
            String ret = arr[head];
            head++;
            if (head >= arr.length){
                head = 0;
            }
            size--;
            System.out.println(name + "读取到了:" + ret + ",当前还剩数据个数为:" + size + "个");
            Thread.sleep(1000);
            this.notifyAll();
            this.wait();
        }else {
            this.notifyAll();
            this.wait();
        }
    }
}
